﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using WxOpenPlatLibCore.Utils;

namespace WxOpenPlatLibCore.Jsapi
{
    public class weixin_helper
    {
        public static string Getaccesstoken(string appid, string secret)
        {
            //LogUtil.WriteLog(" ============ Getaccesstoken =====================");
            if (CacheHelper.Get("__" + appid + "__access_token__") + "" != "")
            {
                return CacheHelper.Get("__" + appid + "__access_token__") + "";
            }
            string urljson = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            UTF8Encoding encoding = new UTF8Encoding();
            string srcString = HttpUtil.Send("", urljson);
            //LogUtil.WriteLog(" ============ srcString =====================" + srcString);
            DeserializeJson dic = new DeserializeJson().GetResult(srcString);
            string access_token = dic.GetString("access_token");
            if (!string.IsNullOrEmpty(access_token))
            {
                CacheHelper.InsertAbsCache("__" + appid + "__access_token__", access_token, 100);
                return access_token;
            }
            return "";
        }

        public static string Getgetticket(string appid, string secret)
        {
            //LogUtil.WriteLog(" ============ Getgetticket =====================");
            if (CacheHelper.Get("__" + appid + "__jsapi_ticket__") + "" != "")
            {
                return CacheHelper.Get("__" + appid + "__jsapi_ticket__") + "";
            }
            string urljson = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" + Getaccesstoken(appid, secret);
            UTF8Encoding encoding = new UTF8Encoding();
            string srcString = HttpUtil.Send("", urljson);
            //LogUtil.WriteLog(" ============ srcString =====================");
            DeserializeJson dic = new DeserializeJson().GetResult(srcString);
            string jsapi_ticket = dic.GetString("ticket");
            if (!string.IsNullOrEmpty(jsapi_ticket))
            {
                CacheHelper.InsertAbsCache("__" + appid + "__jsapi_ticket__", jsapi_ticket, 100);
                return jsapi_ticket;
            }
            return "";
        }

        public static string Getsignature(string appid, string secret, string nonceStr, string timespanstr,string url)
        {
            string str = "jsapi_ticket=" + Getgetticket(appid, secret) + "&noncestr=" + nonceStr + "&timestamp=" + timespanstr + "&url=" + url;// +"&wxref=mp.weixin.qq.com";
            return getSha1(str);
        }

        public static string getNoncestr()
        {
            Random random = new Random();
            return GetMD5(random.Next(1000).ToString(), "GBK");
        }

        public static string getTimestamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        public static string GetMD5(string encypStr, string charset)
        {
            string retStr;
            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();
            //创建md5对象
            byte[] inputBye;
            byte[] outputBye;

            //使用GB2312编码方式把字符串转化为字节数组．
            try
            {
                inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);
            }
            catch (Exception ex)
            {
                inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);
            }
            outputBye = m5.ComputeHash(inputBye);

            retStr = System.BitConverter.ToString(outputBye);
            retStr = retStr.Replace("-", "");
            return retStr.ToLower();
        }

        private static String getSha1(String str)
        {
            //建立SHA1对象
            SHA1 sha = new SHA1CryptoServiceProvider();
            //将mystr转换成byte[] 
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] dataToHash = enc.GetBytes(str);
            //Hash运算
            byte[] dataHashed = sha.ComputeHash(dataToHash);
            //将运算结果转换成string
            string hash = BitConverter.ToString(dataHashed).Replace("-", "");
            return hash.ToLower();
        }

        /// <summary>
        /// 生成微信分享
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="AppSecret"></param>
        /// <param name="title"></param>
        /// <param name="desc"></param>
        /// <param name="imgpath"></param>
        /// <param name="shareurl"></param>
        /// <returns></returns>
        public static string WeiXinScript(string url)
        {
            string appId = "wxb6c977bb4404929e";
            string AppSecret = "887388e94ece2213acb683a93415858c";
            string nonceStr, timespanstr, signature;
            nonceStr = getNoncestr();
            timespanstr = getTimestamp();
            signature = Getsignature(appId, AppSecret, nonceStr, timespanstr,url);
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<script src=\"http://res.wx.qq.com/open/js/jweixin-1.2.0.js\"></script>");
            sb.AppendLine("<script type=\"text/javascript\">");
            sb.AppendLine("    wx.config({");
            sb.AppendLine("        debug: false,");
            sb.AppendFormat("        appId: '{0}',", appId); sb.AppendLine();
            sb.AppendFormat("        timestamp: {0},", timespanstr); sb.AppendLine();
            sb.AppendFormat("        nonceStr: '{0}',", nonceStr); sb.AppendLine();
            sb.AppendFormat("        signature: '{0}',", signature); sb.AppendLine();
            sb.AppendLine("        jsApiList: [");
            sb.AppendLine("            'chooseImage',");
            sb.AppendLine("            'previewImage',");
            sb.AppendLine("            'uploadImage',");
            sb.AppendLine("            'downloadImage',");
            sb.AppendLine("            'openLocation',");
            sb.AppendLine("            'getLocation'");
            sb.AppendLine("        ]");
            sb.AppendLine("    });");
            sb.Append("</script>");
            return sb.ToString();
        }

        public static byte[] WeiXinGetFile(string MEDIA_ID)
        {
            string appId = "wxb6c977bb4404929e";
            string AppSecret = "887388e94ece2213acb683a93415858c";
            string access = Getaccesstoken(appId, AppSecret);
            byte[] data = HttpUtil.Send(string.Format("https://api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", access, MEDIA_ID));
            return data;
        }

    }
}
